<?php

namespace CHOMP\SGIBundle\Controller;

use CHOMP\SGIBundle\Form\EmpresaType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use CHOMP\SGIBundle\Entity\Empresa;
use CHOMP\SGIBundle\Entity\Prioridad;
use CHOMP\SGIBundle\Entity\CuentaAnalitica;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CHOMP\SGIBundle\Services\RolHelper;
use CHOMP\SGIBundle\Services\SessionManager;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\Session\Session;
use	Doctrine\Common\Collections\ArrayCollection;

class EmpresaController extends Controller
{
	/**
	 * 
	 * @var SessionManager
	 * @DI\Inject("session.manager")
	 */
	public $sessionSvc;
	
	/**
	 * 
	 * @var RolHelper
	 * @DI\Inject("rol.helper")
	 */	
	public $rolHelper;

	public function listarAction(Request $request, $page)
	{
		$session = $request->getSession();
		if ($this->sessionSvc->userIsLogged()){
			if($session->get('esAdmin')=='NO'){
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->getAllActivasPorEmpresa($session->get('empresa'));
			}else{
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->getAll();		
			}		
			
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			$this->sessionSvc->setSession('empresas', '');
			return $this->render('CHOMPSGIBundle:Empresa:listar.html.twig', array('empresas' => $paginador));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}	
	


	public function filtrarAction(Request $request, $page)
	{
		if ($this->sessionSvc->userIsLogged()){
			$nombre = $request->get('nombreEmpresa');
			$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->getFiltrado($nombre);
			
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			return $this->render('CHOMPSGIBundle:Empresa:listar.html.twig', array('empresas' => $paginador));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}	



	public function verAction($id)
	{
		if ($this->sessionSvc->userIsLogged()){
			$empresa = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->find($id);
					
			return $this->render('CHOMPSGIBundle:Empresa:ver.html.twig', array('empresa' => $empresa));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}




	public function nuevoAction(Request $request)
	{
		if ($this->sessionSvc->userIsLogged()){
			$empresa = new Empresa();
			$empresa->setBorrado(false);
			$form = $this->createForm(new EmpresaType(), $empresa);
			$form->handleRequest($request);

			$empresas = '';
			
			if ($form->get('save')->isClicked()) {
				if ($form->isValid()) {
	
					$em = $this->getDoctrine()->getManager(); 
					$em->persist($empresa);
					$em->flush();
	
					//Agregar prioridades genericas
					$empresa->addPrioridades(new Prioridad(1, 'Severa', '', 8, $empresa));
					$empresa->addPrioridades(new Prioridad(2, 'Alta', '', 16, $empresa));
					$empresa->addPrioridades(new Prioridad(3, 'Media', '', 24, $empresa));
					$empresa->addPrioridades(new Prioridad(4, 'Baja', '', 32, $empresa));
	
					// Agregar roles genericos
					$this->asignarPermisosGenericos ($empresa->getRoles());
	
					$em->persist($empresa);
					$em->flush();
	
					$this->sessionSvc->setSession('empresas', '');
	
					return $this->redirect($this->generateUrl('empresa_listar'));	
				}
			}

			if ($form->get('continuar')->isClicked()) {
				if ($form->isValid()) {
					$em = $this->getDoctrine()->getManager(); 
					$em->persist($empresa);
					$em->flush();
	
					//Agregar prioridades genericas
					$empresa->addPrioridades(new Prioridad(1, 'Severa', '', 8, $empresa));
					$empresa->addPrioridades(new Prioridad(2, 'Alta', '', 16, $empresa));
					$empresa->addPrioridades(new Prioridad(3, 'Media', '', 24, $empresa));
					$empresa->addPrioridades(new Prioridad(4, 'Baja', '', 32, $empresa));
						
					// Agregar roles genericos
					$this->asignarPermisosGenericos ($empresa->getRoles());
	
					$em->persist($empresa);
					$em->flush();

					$empresas = $this->sessionSvc->getSession('empresas');
					
					if($empresas!=''){
						$empresas = $empresa->getNombre().', '.$empresas;
					}else{
						$empresas = $empresa->getNombre();
					}
					
					$this->sessionSvc->setSession('empresas', $empresas);
					$empresa = new Empresa();
					$empresa->setBorrado(false);
				
					$form = $this->createForm(new EmpresaType(), $empresa);
	
					return $this->render('CHOMPSGIBundle:Empresa:nuevo.html.twig', array(
						'form' => $form->createView(),
						'empresas' => $empresas, 
						));
				}
			}

			if ($form->get('volver')->isClicked()) {
				/*
				return $this->render('CHOMPSGIBundle:Empresa:nuevo.html.twig', array(
						'form' => $form->createView(),
						'empresas' => $empresas,
						));
				*/
				return $this->redirect($this->generateUrl('empresa_listar')); 

			}

			return $this->render('CHOMPSGIBundle:Empresa:nuevo.html.twig', array(
				'form' => $form->createView(),
				'empresas' => $empresas,
				));

		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}



	private function asignarPermisosGenericos($roles){
		$em = $this->getDoctrine()->getManager(); 
		foreach( $roles as $rol){ 
				
			if ($rol->getNombre() == 'Administrador'){
				$rol->addPermisos( $this->rolHelper->insertPermisosForAdministrador($rol->getEmpresa()->getId()) );
				$em->persist($rol);
			}else{
				if ($rol->getNombre() == 'Operador'){
					$rol->addPermisos( $this->rolHelper->insertPermisosForOperador($rol->getEmpresa()->getId()) );
					$em->persist($rol);
				}else{
					if ($rol->getNombre() == 'Coordinador'){
						$rol->addPermisos( $this->rolHelper->insertPermisosForCoordinador($rol->getEmpresa()->getId()) );
						$em->persist($rol);
					}else{
						if ($rol->getNombre() == 'Cliente Externo'){
							$rol->addPermisos( $this->rolHelper->insertPermisosForClienteExterno($rol->getEmpresa()->getId()) );
							$em->persist($rol);
						}else{
							/*
							if($rol->getNombre() == 'Administrador Root'){
								$rol->addPermisos( $this->rolHelper->insertPermisosForAdministradorRoot($rol->getEmpresa()->getId()) );
								$em->persist($rol);
							}
							*/
						}
					}
				}
			}
			
		}
	}

	public function borrarAction($id)
	{
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
			$idsArray = explode (',', $id);
	
			for ($i = 0; $i < count($idsArray); $i++){
				$this->sessionSvc->setSession('array', $idsArray);
				if($idsArray[$i] != 'marcarTodo'){
					$empABorrar = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->find($idsArray[$i]);
					$empABorrar->setBorrado(1);
					$em->persist($empABorrar);
				}				
			}
	
			$em->flush();
					
			return $this->redirect($this->generateUrl('empresa_listar'));	
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}

	public function activarAction($id) {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
			$empresa = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Empresa')->find($id);;
			$empresa->setBorrado(0);
			$em->persist($empresa);
	
			$em->flush();
					
			return $this->redirect($this->generateUrl('empresa_listar'));	
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
	}



    /**
     * Displays a form to edit an existing GrupoSoporte entity.
     *
     * @Route("/editar/{id}", name="empresa_editar")
     * @Method("GET")
     * @Template()
     */
    public function editarAction(Request $request, $id)
    {
		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
			$session = $request->getSession();
			$entity = $em->getRepository('CHOMPSGIBundle:Empresa')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find GrupoSoporte entity.');
			}
	
			$editForm = $this->createEditForm($entity);
			
			return array(
				'entity'      => $entity,
				'edit_form'   => $editForm->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}
    }

    /**
    * Creates a form to edit a Empresa entity.
    *
    * @param Usuario $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Empresa $entity)
    {
        $form = $this->createForm(new EmpresaType(), $entity, array( 
            'action' => $this->generateUrl('empresa_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        return $form;
    }
    /**
     * Edits an existing Usuario entity.
     *
     * @Route("/empresa/{id}", name="empresa_update")
     * @Method("PUT")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CHOMPSGIBundle:Empresa')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Empresa entity.');
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('empresa_ver', array('id' => $id)));
        }

		return $this->render('CHOMPSGIBundle:Empresa:editar.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        ));
    }

	protected function getAllFormErrorMessages($form)
	{	
		$retval = array();
		foreach ($form->getErrors() as $key => $error) {
        		if($error->getMessagePluralization() !== null) {
            			$retval['message'] = $this->get('translator')->transChoice(
                		$error->getMessage(), 
                		$error->getMessagePluralization(), 
                		$error->getMessageParameters(), 
                		'validators'
            		);
        		} else {
            			$retval['message'] = $this->get('translator')->trans($error->getMessage(), array(), 'validators');
        		}
    		}
    		foreach ($form->all() as $name => $child) {
        		$errors = $this->getAllFormErrorMessages($child);
        			if (!empty($errors)) {
           				$retval[$name] = $errors; 
        			}
    		}
    	return $retval;
	}


    // flor test
    public function sendEmailAction(){

        $mailer = $this->get('my_mailer');
        $response = new Response();
        $response -> setContent($mailer->sendEmail('flor@flor.com'));
        return $response;
    }
	
	public function mailAction($name)
	{
		$message = \Swift_Message::newInstance()
			->setSubject('Hello Email')
			->setFrom('corvalan4@hotmail.com')
			->setTo('corvalan4@gmail.com')
			->setBody(
				$this->renderView(
					'CHOMPSGIBundle:Empresa:email.txt.twig'
				)
			)
		;
			
		$this->get('mailer')->send($message);

        return $this->redirect($this->generateUrl('empresa_listar'));
	}
}
